<?php

namespace App\Models;

class Topic extends Model
{
    protected $fillable = ['title', 'body', 'category_id', 'excerpt', 'slug'];

    //话题->分类（1->1）
    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id');
    }

    //话题->用户（1->1）
    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');//当前模型的外键,关联模型的主键 hasOne相反
    }

    public function scopeWithOrder($query,$order)
    {
        //不同的排序使用，使用不同的数据读取逻辑
        switch ($order) {
            case "recent":
                $query->recent();
                break;
            default:
                $query->recentReplied();
                break;
        }
        return $query->with('user','category');
    }

    public function scopeRecentReplied($query)
    {
        return $query->orderBy('updated_at','desc');
    }

    public function scopeRecent($query)
    {
        return $query->orderBy('created_at','desc');
    }

    public function link($param = [])
    {
        return route('topics.show',array_merge([$this->id,$this->slug],$param));
    }

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }


}
